import { useState, useRef, useCallback } from 'react';
import { sendMessageWithContext } from '../api/ai';
import type { FileItem } from '../api/ai';
import { fileToBase64, getFilePreview, validateFileSize, validateFileType } from '../utils/fileUtils';

export interface ChatMessage {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  timestamp: number;
  files?: FileItem[];
}

export const useChat = () => {
  const [chatList, setChatList] = useState<ChatMessage[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 滚动到底部
  const scrollToBottom = useCallback(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, []);

  // 处理文件上传
  const processFiles = async (files: FileList): Promise<FileItem[]> => {
    const fileItems: FileItem[] = [];

    for (let i = 0; i < files.length; i++) {
      const file = files[i];

      // 验证文件
      if (!validateFileType(file)) {
        throw new Error(`不支持的文件类型: ${file.name}`);
      }

      if (!validateFileSize(file)) {
        throw new Error(`文件过大: ${file.name}，最大支持10MB`);
      }

      try {
        // 获取预览
        const preview = await getFilePreview(file);

        // 如果是图片或PDF，转换为base64
        let base64Data = '';
        if (file.type.startsWith('image/') || file.type === 'application/pdf') {
          base64Data = await fileToBase64(file);
        }

        fileItems.push({
          id: `${Date.now()}-${i}`,
          file,
          preview: base64Data || preview
        });
      } catch (error) {
        console.error('处理文件失败:', error);
        throw new Error(`处理文件失败: ${file.name}`);
      }
    }

    return fileItems;
  };

  // 发送消息（支持文件）
  const sendMessage = async (content: string, files: FileItem[] = []) => {
    if (!content.trim() && files.length === 0) return;

    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      role: 'user',
      content: content.trim(),
      timestamp: Date.now(),
      files: files.length > 0 ? files : undefined,
    };

    setChatList(prev => [...prev, userMessage]);
    setIsLoading(true);

    try {
      // 构建消息历史
      const messages = [...chatList, userMessage].map(msg => ({
        role: msg.role,
        content: msg.content
      }));

      const response = await sendMessageWithContext(messages, files);

      const assistantMessage: ChatMessage = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: response,
        timestamp: Date.now(),
      };

      setChatList(prev => [...prev, assistantMessage]);
    } catch (error) {
      console.error('发送消息失败:', error);
      const errorMessage: ChatMessage = {
        id: (Date.now() + 1).toString(),
        role: 'assistant',
        content: '抱歉，服务暂时不可用，请稍后再试。',
        timestamp: Date.now(),
      };
      setChatList(prev => [...prev, errorMessage]);
    } finally {
      setIsLoading(false);
    }
  };

  // 发送带文件的消息
  const sendMessageWithFiles = async (content: string, files: FileList) => {
    try {
      const processedFiles = await processFiles(files);
      await sendMessage(content, processedFiles);
    } catch (error) {
      console.error('发送文件消息失败:', error);
      throw error;
    }
  };

  // 清空聊天记录
  const clearChat = () => {
    setChatList([]);
  };

  return {
    chatList,
    isLoading,
    messagesEndRef,
    sendMessage,
    sendMessageWithFiles,
    clearChat,
    scrollToBottom,
  };
};
